// index page
// ============

define(['zepto', 'utils', 'wxpay',  'utils', 'qiniu', 'qiniuPlayer','sliderRuler', 'sui', 'countDown' ], function($, utils, wxpay, utils, qiniu, QPlayer) {
      return {
        init : function(data) {
          this.betId = data.betId;
          this.afterVideo = data.afterVideo;
          this.userId = data.userId;
          this.player;
          this.afterPlayer;
          
          utils.configWeixin(data.jsConfig, true, {
            name: "赌你会瘦",
            desc: "您的小伙伴邀请您参加人马君赌你会瘦活动，快来一起瓜分万元奖金吧~",
            link: data.url ? data.url : window.__CTX__.domain + "/welcome",
            cover : data.avatar
          });
          
          this.bindUpload();
          this.bindBetOpen();
          this.exampleVedioModal();
          this.initSlideRuler();
          
        },
        
        bindUpload: function(config) {
          var that = this;
          
          $(document).on("change", "input[name='selectVideo']", function(e){
            
            $.modal({
              title:  '开始上传',
              text: '<p class="processing">进度：0%</p>',
              buttons: []
            })
            var $input = this;
            
            $.ajax({
              
              url: window.__CTX__.cloudToken,
              // The name of the callback parameter, as specified by the YQL service
              jsonp: "callback",
              // Tell jQuery we're expecting JSONP
              dataType: "jsonp",
              // Work with the response
              success: function( response ) {
                var token = response.token;
                var name = $input.files[0].name;
                var nameSplit = name.split(".");
                var surfix = nameSplit[nameSplit.length -1];
                var key = new Date().getTime() + "." + surfix;
                that.uploadKey = key;
                var putExtra = {
                        fname: name,
                        params: {},
                        mimeType: null
                      };
                
                var config = {
                        useCdnDomain: true,
                        disableStatisticsReport: false,
                        retryCount: 6,
                        region: null
                      };
                var observable = qiniu.upload($input.files[0], key, token, putExtra, config);
                observable.subscribe(function(response){
                  let total = response.total;
                  var processing = parseInt(total.percent)
                  $(".processing").html("进度：" + processing + "% ");
                  if(processing == 100) {
                    $.closeModal();
                    if(that.afterPlayer) that.afterPlayer.destroy();
                      
                      $("input[name='selectVideoPath']").val(window.__CTX__.cloudHost + "/" + key);
                      $(".video-uploadarea").addClass("hide");
                      $(".video-showarea").removeClass("hide");
                      
                      that.afterPlayer = new QPlayer({
                        url: window.__CTX__.cloudHost + "/" + key,
                        container: document.getElementById("showVideo"),
                        defaultViewConfig: {
                          showControls: true,
                        }
                      });
                  }
                });
              },
              fail: function(e) {
                $.taost("选择失败");
                window.location.reload();
              }
            });
            
          })
          
          $(document).on("click", ".close", function(e){
            $("input[name='selectVideoPath']").val('');
            $("input[name='selectVideo']").val("");
            $(".video-uploadarea").removeClass("hide");
            $(".video-showarea").addClass("hide");
            that.afterPlayer.destroy();
          })
       },
        
        bindBetOpen: function() {
          var that = this;
          var currentVideo = $("#beforeShowVideo").data("video");
          if(currentVideo) {
            that.player = new QPlayer({
              url: currentVideo + '?avvod/m3u8/s/960x640/vb/1000k',
              container: document.getElementById("beforeShowVideo"),
              defaultViewConfig: {
                showControls: true,
              }
            });
          }
          
          $(document).on('click', '#submit', function(e) {
            e.preventDefault();
            var videoPath = $("input[name='selectVideoPath']").val();
            if(!videoPath) {
              $.toast("请先上传视频");
              return;
            }
            
            var $weight = $("input[name='weight']");
            if(!$weight || !$weight.val()) {
              $.toast("请填写体重");
              return;
            }
            
            $.showPreloader('正在上传最终挑战结果')
            $.post(window.__CTX__.root + '/profile/bets/' + that.betId + '/close?weight=' + $weight.val() + "&afterVedio=" + videoPath)
            .done(function(response) {
              $.hidePreloader();
              utils.processResult(response, function(data) {
                window.location.href=window.__CTX__.root + '/profile/bets/' + that.betId;
              }, function() {
                $.toast(result.message || '上传最终挑战结果失败')
              })
            })
          })
        },
        exampleVedioModal: function() {
          var that = this;
    	  $(document).on('click','#exampleVedio', function () {
    	    $.modal({
    	      text: '<div id="exampleVideo" style="width: 100%; height: 11rem;"></div>',
    	      extraClass: 'example-video',
    	      buttons: [
    	        {
    	          text: '关闭',
    	        }
    	      ]
    	    })
    	    
    	    that.examplePlayer = new QPlayer({
              url: "https://prod.qiniu.fit-start.co/weight-video-example.mp4",
              container: document.getElementById("exampleVideo"),
              defaultViewConfig: {
                showControls: true,
              }
            });
    	  });
    	  
        },
        initSlideRuler: function() {
            var currentValue = $(".slider-ruler .value").data("weight") ? $(".slider-ruler .value").data("weight") : 50;
            new sliderRuler({
                  el: document.querySelector('#slider-box'),
                  maxValue: 120,
                  minValue: 30,
                  canvasWidth: 300,
                  canvasHeight: 50,
                  fontSize: 12,
                  currentValue: currentValue,
                  handleValue: function(value) {
                    $(".value").find("span").html(value);
                    $("input[name='weight']").val(value);
                  },
                  precision: 0.1
     		    }
     		  );
          }
      }
    })